const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const Role = require('../models/roleSchema')
const util = require('../utils/util')
const md5 = require('md5')

router.prefix('/roles')

router.get('/allList', async (ctx) => {
  const list = await Role.find({}, '_id, roleName')

  ctx.body = util.success({ list })
})

router.get('/list', async (ctx) => {
  const { roleName } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)
  let params = {}
  if (roleName) {
    params.roleName = roleName
  }
  const query = Role.find(params)
  const list = await query.skip(skipIndex).limit(page.pageSize)
  const total = await Role.countDocuments(params)

  ctx.body = util.success({
    list,
    page: {
      ...page,
      total
    }
  })
})

router.post('/operate', async (ctx) => {
  const { roleName, remark, _id, action } = ctx.request.body
  let res, info
  if (action === 'create') {
    res = await Role.create({ roleName, remark })
    info = '创建成功'
  } else if (action === 'edit') {
    let params = { roleName, remark, updateTime: new Date() }
    res = await Role.findByIdAndUpdate(_id, params)
    info = '更新成功'
  } else if (action === 'delete') {
    res = await Role.findByIdAndRemove(_id)
    info = '删除成功'
  }
  ctx.body = util.success(res, info)
})

router.post('/update/permission', async (ctx) => {
  const { _id, permissionList } = ctx.request.body

  const params = { permissionList, updateTime: new Date() }
  await Role.findByIdAndUpdate(_id, params)
  ctx.body = util.success('', '权限设置成功')
})

module.exports = router
